<template>
	<view>
		<yingbing-video
			v-if="src && this.info.liveUrl"
			ref="video"
			muted
			:controls="controls"
			:barrage-show="barragesShow"
			title="测试视频"
			:src="src"
			@error="handleError"
			autoplay
		/>
		<!-- 	<yingbing-video v-if="src" ref="video" :poster="poster" muted controls="true" title="测试视频">
			<source :src="src" type="video/mp4" />
		</yingbing-video> -->
		<video v-else style="width: 100%" :src="src" ref="video" @click="playVideo" :poster="poster" controls="true">
			<source :data-src="src" type="video/mp4" />
		</video>
		<!-- 视频和课程信息 -->
		<view class="info-box">
			<view v-if="info.adCourse" class="course-name">
				<text class="name">{{ info.adCourse.name }}</text>
				<view class="hot-box">
					<image style="width: 30rpx; height: 30rpx" src="../../static/hot.svg" mode=""></image>
					<text>{{ info.adCourse.readCount }}学习热度</text>
				</view>
			</view>
			<u-button @click="showHomeworkModal" type="primary" size="small" text="作业提交"></u-button>
			<text class="title">讲师</text>

			<view class="teacher-box">
				<image style="width: 80rpx; height: 80rpx" src="../../static/woman.svg" mode=""></image>
				<text>{{ info.teacherName }}</text>
			</view>
			<!-- 章节列表 -->
			<view class="course-list">
				<text class="title">直播课程</text>
				<view v-if="info.chapterList">
					<view v-for="chapters in info.chapterList" :key="chapters.courseId">
						<text style="font-weight: bold; padding-top: 20rpx">{{ chapters.name }}</text>
						<view v-if="chapters.children && chapters.children.length > 0">
							<view class="course-item">
								<view
									class="item"
									v-for="item in chapters.children"
									:key="item.courseId"
									:class="{ isActive: item.name === curChapterName }"
									@click="handleChapter(item)"
								>
									<text>{{ item.name }}</text>
									<view v-if="item.url" class="time">
										<image style="width: 30rpx; height: 30rpx" src="../../static/time.svg" mode=""></image>
									</view>
									<view v-else class="no_video">暂无视频</view>
								</view>
							</view>
						</view>
					</view>
				</view>
			</view>
			<!-- 直播描述 -->
			<view v-if="info.adCourse" class="course-desc">
				<text class="title">直播描述</text>
				<view class="live-desc" v-html="info.adCourse.content"></view>
			</view>
		</view>

		<!-- 作业提交弹框 -->
		<view v-if="showModal" class="modal-overlay">
			<view class="modal">
				<view class="modal-header">
					<text>提交作业</text>
				</view>

				<view class="modal-body">
					<view class="form-item">
						<label>选择作业</label>
						<picker mode="selector" :range="jobList" range-key="name" @change="handlePickerChange">
							<view class="picker">
								{{ selectedJobIndex !== null ? jobList[selectedJobIndex].name : '请选择作业' }}
							</view>
						</picker>
					</view>
					<view class="form-item">
						<label>上传作业图片</label>
						<u-button type="primary" size="small" @click="chooseImage">上传图片</u-button>
						<view>{{ form.homeworkImages.length }} 张图片已上传</view>
						<view class="image-preview">
							<view class="image-preview">
								<image v-for="(image, index) in form.homeworkImages" :key="index" :src="image" mode="aspectFill" class="uploaded-image"></image>
							</view>
						</view>
					</view>
					<view class="form-item">
						<label>作业描述</label>
						<textarea v-model="form.homeworkDescription" maxlength="150" placeholder="请输入作业描述"></textarea>
						<view>{{ form.homeworkDescription.length }}/150</view>
					</view>
				</view>

				<view class="modal-footer">
					<u-button class="cancel-button" @click="cancel">取消</u-button>
					<u-button class="submit-button" @click="submitHomework">提交</u-button>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import env from '@/config/envConfig.js';
import * as qiniu from 'qiniu-js';
import rsa from '@/config/rsa.js';
import flvjs from 'flv.js';
import { listToTree } from '../../config/common';

export default {
	data() {
		return {
			src: '',
			flvConfig: {
				cors: true
			},
			curChapterName: '',
			barragesShow: true,
			controls: true,
			info: {},
			emptyVisible: false,
			emptyMessage: '',
			courseId: '',
			orderNum: '',
			teacherId: '',
			selectedJobIndex: null, // 选中的作业索引
			teacherAdId: '',
			jobList: [],
			form: {
				homeworkId: null,
				chapterId: null,
				homeworkImages: [],
				homeworkDescription: ''
			},
			showModal: false
		};
	},
	onLoad(options) {
		console.log('options', options);
		// var url = window.location.href;
		// url = url.replace('=', '');
		// let urls = url.split('?');
		// if (urls.length == 2) {
		// 	this.courseId = urls[1];
		// }

		this.courseId = options.courseId;
		this.orderNum = options.orderNum;
		this.teacherId = options.teacherId; // 添加 teacherId
		this.getStudentInfo();
		this.getJobList();
	},
	methods: {
		playVideo() {
			// 点击视频时触发播放
			const videoElement = this.$refs.video;
			videoElement.play(); // 调用原生的播放功能
		},
		fullscreen() {
			this.$refs.video.launchFullscreen();
		},
		handleError(e) {
			if (e.type == 'networkError') {
				if (e.response.code == 404) {
					uni.showToast({
						title: '当前暂无直播',
						icon: 'none'
					});
				}
			} else {
				uni.showToast({
					title: e.type,
					icon: 'none'
				});
			}
		},
		handleFullscreenChange(e) {
			if (e.fullscreen) {
				this.controls = true;
			} else {
				this.controls = false;
			}
		},
		getStudentInfo() {
			const httpData = {
				courseId: this.courseId ? this.courseId : '',
				orderNum: this.orderNum ? this.orderNum : '',
				teacherId: this.teacherId ? this.teacherId : ''
			};

			uni.$u.http
				.post('/user/info/student', httpData, {
					custom: {
						load: false,
						auth: true
					}
				})
				.then((res) => {
					const { chapterList, ...rest } = res;
					this.info = {
						...rest,
						chapterList: listToTree(chapterList)
					};
					this.info.adCourse.content = this.info.adCourse.content.replace(/\<img(.*?)src/g, '<img style="max-width:100%!important;height:auto;display:block;" src');
					this.info.adCourse.content = this.info.adCourse.content.replace(/\<p/g, '<p style="line-height:1.8;word-break: break-all;"');
					this.courseName = this.info.adCourse.name;

					// Check if liveUrl exists and play the live stream
					if (this.info.liveUrl) {
						const url = rsa.decryptByPublicKey(this.info.liveUrl);
						this.src = url;
						console.log('this.src', this.src);
						this.poster = ''; // Remove any poster for live stream
						this.emptyVisible = false;
					} else {
						// If live stream is not available, play the first chapter
						if (this.info.chapterList && this.info.chapterList.length > 0) {
							const firstChapter = this.info.chapterList[0].children[0];
							if (firstChapter) {
								this.handleChapter(firstChapter);
							} else {
								this.emptyVisible = true;
								this.emptyMessage = '暂无录播视频';
							}
						} else {
							this.emptyVisible = true;
							this.emptyMessage = '当前暂无直播或录播';
						}
					}
				})
				.catch((err) => {
					console.error(err);
					this.emptyVisible = true;
					this.emptyMessage = '加载失败，请重试';
				});
		},

		handleChapter(chapter) {
			if (!chapter.url) {
				uni.showToast({
					title: '暂无视频',
					icon: 'none'
				});
				return;
			}

			this.curChapterName = chapter.name;
			const url = rsa.decryptByPublicKey(chapter.url); // 获取解密后的视频 URL
			const posterUrl = chapter.image; // 获取封面图，如果没有用默认封面
			console.log('posterUrl', posterUrl);
			this.poster = posterUrl; // 设置封面图
			this.src = url; // 保存视频地址，但不自动加载

			let httpData = {
				chapterId: chapter.id
			};

			// 更新观看记录的请求
			uni.$u.http
				.post('/user/info/watchSave', httpData, {
					custom: {
						load: false,
						auth: true
					}
				})
				.then((res) => {});
		},
		getJobList() {
			uni.$u.http
				.post(
					'/user/info/courseWorkList',
					{
						courseId: this.courseId
					},
					{
						custom: {
							load: false,
							auth: true
						}
					}
				)
				.then((res) => {
					this.jobList = res || [];
				})
				.catch((err) => {
					uni.showToast({ title: '加载错误~', icon: 'none' });
				});
		},
		showHomeworkModal() {
			if (this.jobList.length === 0) {
				uni.showToast({ title: '暂无作业', icon: 'none' });
				return;
			}
			this.showModal = true;
		},
		cancel() {
			this.showModal = false;
			this.form = {
				homeworkId: null,
				homeworkImages: [],
				homeworkDescription: ''
			};
		},
		submitHomework() {
			if (this.form.homeworkId === null || this.form.homeworkDescription.trim() === '') {
				uni.showToast({ title: '请填写完整信息', icon: 'none' });
				return;
			}

			uni.$u.http
				.post(
					'/user/info/submitWork',
					{
						chapterId: this.form.chapterId,
						courseId: this.courseId,
						workId: this.form.homeworkId,
						url: JSON.stringify(this.form.homeworkImages),
						name: this.form.homeworkDescription
					},
					{
						custom: {
							load: false,
							auth: true
						}
					}
				)
				.then(() => {
					this.showModal = false;
					uni.showToast({ title: '提交成功', icon: 'success' });
				})
				.catch((err) => {
					uni.showToast({ title: '提交失败，请重试', icon: 'none' });
				});
		},
		// chooseImage() {
		// 	uni.$u.http
		// 		.post(
		// 			'/comm/getUpToken',
		// 			{},
		// 			{
		// 				custom: { load: false, auth: true }
		// 			}
		// 		)
		// 		.then((res) => {
		// 			const upToken = res;
		// 			uni.chooseImage({
		// 				count: 5 - this.form.homeworkImages.length,
		// 				sizeType: ['compressed', 'original'],
		// 				sourceType: ['album', 'camera'],
		// 				success: (chooseImageRes) => {
		// 					const filePaths = chooseImageRes.tempFilePaths;
		// 					console.log('chooseImageRes', chooseImageRes);
		// 					// 使用箭头函数，确保 this 的上下文正确
		// 					filePaths.forEach((filePath) => {
		// 						const observable = qiniu.upload(filePath, null, upToken, {
		// 							mimeType: ['image/jpeg', 'image/png'] // 确保 MIME 类型正确
		// 						});
		// 						observable.subscribe({
		// 							next: undefined,
		// 							error: (err) => {
		// 								uni.showToast({ title: '图片上传失败', icon: 'none' });
		// 							},
		// 							complete: ({ key }) => {
		// 								// 拼接图片链接并更新 homeworkImages
		// 								this.form.homeworkImages = [...this.form.homeworkImages, env.qiniuDomain + key];
		// 								console.log('homeworkImages', this.form.homeworkImages);
		// 								uni.showToast({ title: '图片上传成功', icon: 'success' });
		// 							}
		// 						});
		// 					});
		// 				}
		// 			});
		// 		})
		// 		.catch((err) => {
		// 			uni.showToast({ title: '获取上传凭证失败', icon: 'none' });
		// 		});
		// },
		chooseImage() {
			uni.chooseImage({
				count: 5 - this.form.homeworkImages.length, // 限制最多选择5张
				sizeType: ['compressed', 'original'], // 可以选择压缩图和原图
				sourceType: ['album', 'camera'], // 可以从相册选择或直接拍照
				success: (chooseImageRes) => {
					const tempFiles = chooseImageRes.tempFiles;
					tempFiles.forEach((file) => {
						this.uploadImageToQiniu(file); // 使用文件对象直接上传
					});
				},
				fail: (err) => {
					uni.showToast({ title: '图片选择失败', icon: 'none' });
				}
			});
		},

		uploadImageToQiniu(file) {
			// 获取七牛云上传Token
			uni.$u.http
				.post('/comm/getUpToken', {}, { custom: { load: false, auth: true } })
				.then((res) => {
					const upToken = res;

					// 通过七牛 SDK 上传文件
					const observable = qiniu.upload(
						file, // 使用文件路径进行上传
						null,
						upToken,
						{ mimeType: ['image/jpeg', 'image/png'] },
						{ fname: file.name } // 传递文件名称
					);

					observable.subscribe({
						next: undefined, // 上传过程中，不做处理
						error: (err) => {
							uni.showToast({ title: '图片上传失败', icon: 'none' });
							console.error('Upload Error:', err);
						},
						complete: ({ key }) => {
							const uploadedImageUrl = `${env.qiniuDomain}/${key}`;
							this.form.homeworkImages = [...this.form.homeworkImages, uploadedImageUrl];
							uni.showToast({ title: '图片上传成功', icon: 'success' });
						}
					});
				})
				.catch((err) => {
					uni.showToast({ title: '获取上传凭证失败', icon: 'none' });
					console.error('Token Error:', err);
				});
		},
		handlePickerChange(event) {
			const selectedIndex = event.detail.value;
			this.selectedJobIndex = selectedIndex;
			const selectedJob = this.jobList[selectedIndex];
			this.form.homeworkId = selectedJob.id;
			this.form.chapterId = selectedJob.chapterId;
		}
	},
	onReady() {
		setTimeout(() => {
			this.barragesShow = false;
		}, 100);
	}
};
</script>

<style lang="scss" scoped>
.title {
	position: relative;
	display: inline-block;
	font-size: 30rpx;
	font-weight: bold;
	padding-left: 16rpx;
	margin-bottom: 30rpx;
	margin-top: 20rpx;

	&::before {
		content: '';
		position: absolute;
		left: 0px;
		top: 10%;
		width: 6rpx;
		border-radius: 4rpx;
		background: #3a85ee;
		height: 80%;
	}
}

image {
	margin-right: 10rpx;
}

.info-box {
	font-size: 26rpx;
	padding: 20rpx;
	color: #666;
}

.isActive {
	color: #3a85ee;
}

.course-name {
	margin-bottom: 32rpx;

	.name {
		font-size: 36rpx;
		font-weight: bold;
	}

	display: flex;
	justify-content: space-between;
	align-items: center;

	.hot-box {
		display: flex;
		align-items: stretch;
		font-size: 24rpx;
	}
}

.teacher-box {
	margin-top: 20rpx;
	display: flex;
	align-items: center;
}

.course-list {
	margin-top: 32rpx;

	.course-item {
		display: flex;
		flex-direction: column;
		padding: 16rpx;

		.item {
			display: flex;
			margin: 21rpx 0rpx;
			justify-content: space-between;
			align-items: center;

			.time {
				display: flex;
				align-items: center;
			}
		}
	}
}
.form-item {
	margin-bottom: 20rpx;
	display: flex;
	flex-direction: column;
	label {
		font-size: 30rpx;
		color: #666;
		margin-bottom: 10rpx;
	}
}
.picker {
	padding: 15rpx;
	border: 1rpx solid #ddd;
	border-radius: 12rpx;
	font-size: 30rpx;
	color: #333;
	background-color: #f9f9f9;
}

.image-preview {
	display: flex;
	flex-wrap: wrap;
	gap: 10rpx; /* 使用 gap 简化图片间距 */
	margin-top: 10rpx;
	.uploaded-image {
		width: 150rpx;
		height: 150rpx;
		border-radius: 10rpx;
		border: 1rpx solid #ddd;
	}
}
textarea {
	width: 100%;
	height: 150rpx;
	padding: 15rpx;
	border: 1rpx solid #ddd;
	border-radius: 12rpx;
	font-size: 28rpx;
	color: #333;
	background-color: #f9f9f9;
	box-sizing: border-box;
	resize: none; /* 禁止手动调整大小 */
}
.modal-overlay {
	z-index: 999;
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: rgba(0, 0, 0, 0.5);
	display: flex;
	justify-content: center;
	align-items: center;
}
.modal-content {
	width: 85%;
	max-width: 600rpx;
	background-color: white;
	border-radius: 20rpx; /* 增加圆角 */
	padding: 30rpx;
	box-shadow: 0 8px 16px rgba(0, 0, 0, 0.2); /* 添加阴影效果 */
}
.modal {
	background: #fff;
	width: 90%;
	max-width: 500px;
	padding: 20rpx;
	border-radius: 10px;
	box-shadow: 0 5px 15px rgba(0, 0, 0, 0.3);
}

.modal-header {
	font-size: 36rpx;
	font-weight: bold;
	margin-bottom: 20rpx;
	text-align: center;
	color: #333;
}

.modal-body {
	margin-top: 20rpx;
}

.modal-footer {
	display: flex;
	justify-content: space-between;
	margin-top: 20rpx;
}

.cancel-button,
.submit-button {
	width: 45%; /* 调整按钮的宽度 */
	height: 50rpx;
	font-size: 30rpx;
	border-radius: 12rpx;
	color: white;
	text-align: center;
	line-height: 50rpx;
	transition: background-color 0.3s ease;
}

.cancel-button {
	background-color: #999; /* 统一为灰色按钮 */
}

.cancel-button:hover {
	background-color: #888; /* 悬停时按钮颜色 */
}

.submit-button {
	background-color: #3a85ee; /* 蓝色提交按钮 */
}

.submit-button:hover {
	background-color: #3367d6; /* 悬停效果 */
}
.uploaded-image {
	width: 60rpx;
	height: 60rpx;
	border-radius: 5rpx;
	margin-right: 10rpx;
	margin-top: 10rpx;
}
</style>
